/*
NAME: 
DESCRIPTION: ;
PARAMETER:
    [
        {
			name : 'ref_step',
			title : '参考step',
			type : 'LineEdit',
			property : {tool_tip : '参考step，默认是orig'},
		},
		{
			name : 'current_step',
			title : '当前step',
			type : 'LineEdit',
			property : {tool_tip : '当前sitep,默认是net'},
		},
		{
            name : 'auto_save',
			title : '自动保存',
            type : 'RadioBox',
            property : {
				item_list:[
					{name:'yes',text:'YES'},
					{name:'no',text:'NO'},
				],
				tool_tip:'是否自动保存料号开关'
			}
        }
	]
	
 VERSION_HISTORY:
	V1.00 2020-04-27 Carver
	    1.新版本
		
 HELP:
 	<html><body bgcolor="#DDECFE">
		<font size="3" color="#003DB2"><p>功能简介</p></font>
		<p> 网络对比 </p>
		<br>
		<font size="3" color="#003DB2"><p>参数配置</p></font>
		<p> </p>
		<br>
		<font size="3" color="#003DB2"><p>注意事项</p></font>
		<p> 无 </p>
		<br>
	</body></html>	
*/
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
console.log("=============================>网络比对");
// 引入模块 包
var $ = require('topcam.scriptfunc').argv();
var fs = require('fs');
var _ = require('lodash');
var mode = $.ikm ? "topcam" : "aimdfm";
var IKM = $.ikm; 
if (IKM==undefined ) { IKM = require('topcam.ikm6')($) }
var GEN = $.gen;
var GUI = $.gui || {};
var Job = $.job || $.job_name;
var JobId = $.job_id;
var db = $.db || IKM.db
var PAR = {}
if ($.par) {
	PAR = $.par
} else if ($.hasOwnProperty('script_parameter')){
	PAR = JSON.parse($.script_parameter);
}
if (mode === "aimdfm") {
	var database = require("topsin.database");
	database.addConnection($.conf.database_conf, "DFM");
	var QDfm = database.query("DFM");
	$.QDfm = QDfm;
	if ($.conf.product_type == "aimdfm") {
		QDfm.updateRow({
			table: "pdm_aimdfm_task",
			data: {
				current_process_title: $.process_title
			},
			where: { id: $.task_id }
		});
	}
}
var Status = 'ok';
var resultData = [];
try {
	var par = PAR;
	var default_par = {
        ref_step: 'orig',
        current_step: 'net',
        auto_save: "No",
        units: 'mm',
	}
	for(var key in default_par){  // 设置默认属性
		if (!par.hasOwnProperty(key) || par[key] == ""){
			par[key] = default_par[key]
		}
    }
    
	if(_.isEmpty(Job)){throw "参数Job不存在"}
	var job = Job.toLowerCase()
	if(!GEN.isJobExists({job:job})){throw "料号"+job+"不存在"}
	if(!GEN.isJobOpen({job:job})){ GEN.openJob({job:job}) }
    if(mode == "aimdfm"){
        if(GEN.checkInout({job:job,mode:"test"}) != 0){ throw "the job check" }
        GEN.checkInout({job:job,mode:"out"});
    }
	
	var stepList = GEN.getStepList({job:job});

	// step不存在报异常
	var ref_step = par.ref_step;
	var current_step = par.current_step;

	var ref_exist = 0;
	var cur_exist = 0;

	stepList.forEach(function(step){
		if(step == ref_step || step.indexOf(ref_step) != -1){
			ref_exist = 1
		}
		if(step == current_step || step.indexOf(current_step) != -1){
			cur_exist = 1
		}
	})

	if(ref_exist == 0){
		throw 'step ' + ref_step + ' is not Exist!'
	}
	if(cur_exist == 0){
		throw 'step ' + current_step + ' is not Exist!'
	}

	// 区分ref-step和current-step是否带有字母后缀，并一一对应
	var curReg = new RegExp("^"+current_step+"([a-z]+)*","ig");
	var curStep = stepList.reduce(function(a, b){			
		if(curReg.test(b)){
			a[b] = '';
		}

		return a;
	}, {})

	var refReg = new RegExp("^"+ref_step,"ig");
	var compareStep = stepList.reduce(function(a, b){
		if(refReg.test(b)){
			var azRef = b.split(ref_step)[1].trim();
			_.keys(curStep).forEach(function(cur){
				var azCur = cur.split(current_step)[1].trim();
				if(azRef == azCur){
					a[cur] = b;
				}
			})
		}

		return a;
	}, curStep)
	// 网络对比
	_.keys(compareStep).forEach(function(cur){
		// 将ref step和current step的type都设置成current
		GEN.COM('netlist_recalc',{job:job, step:compareStep[cur], type:'cur', display:'top',layer_list:''}); 
		GEN.COM('netlist_recalc',{job:job, step:cur, type:'cur', display:'bottom',layer_list:''});
		GEN.netlistPageOpen()
		
		var netCompareResult = GEN.netlistCompare({
			job1:job,
			step1:cur,
			type1:'cur',
			job2:job,
			step2:compareStep[cur],
			type2:'cur'
		})

		var outPutInfo = {
			current_step: cur,
			ref_step: compareStep[cur], 
			shorted: netCompareResult["shorted"],
			broken: netCompareResult["broken"],
			missing: netCompareResult["missing"],
			extra: netCompareResult["extra"], 
		}

		// 结果输出
		if(Number(netCompareResult['shorted']) > 0 || Number(netCompareResult['broken']) > 0){
			interrupt('error', '网络对比报错!', outPutInfo)
			IKM.msg("请确认处理网络问题")
		}else{
			resultData.push({ type: "info", title: "网络对比成功", detail: [{desc: _.toString(outPutInfo)}]})
			IKM.msg("比对无问题")
		}
	})

	// 保存 
	if(/yes/ig.test(par.auto_save)){
		GEN.checkInout({job:job,mode:"out"})  // 结束保存料号 关闭料号
		GEN.saveJob({ job: job });
		GEN.checkInout({job:job,mode:"in"})
		GEN.closeJob({job:job})
	} else {
		GEN.checkInout({job:job,mode:"in"})
	}

	if (mode === "aimdfm") {
		$.QDfm.updateRow({
			table: "pdm_aimdfm_task",
			data: {
				progress: 33.33
			},
			where: { id: $.task_id }
		});
		if (GEN.hasError()) {
			Status = 'error';
			resultData.push({ type: "error", title: "GEN错误!", detail: [{ desc: _.join(GEN.STATUS, "\n") }] });
			return {
				status: Status,
				result_data: resultData
			};
		} else {
			resultData.push({ type: "info", title: "操作完成, 请注意检查!" });
			return {
				status: Status,
				result_data: resultData
			};
		}
	}else {
		return "Done"
	} 
} catch (e) {
	IKM.msg(_.join(GEN.STATUS, "\n"))
	IKM.msg(e)
    Status = 'error';
    resultData.push({type: "error", title: "脚本执行出错!", detail: [{desc: _.toString(e)}]});
	return (mode === "aimdfm") ? {status: Status, result_data: resultData} : "Error";
}


function interrupt(type, title, detail){  // 自定义return
    resultData.push({type: type, title: title, detail: [{desc: _.toString(detail)}]});
    return {status: type, result_data: resultData};
}